<template>
  <div class="chart-inst">
    <template v-if="inited === true">
      <div
        class="label-item"
        v-for="(item, index) in option.data"
        :style="getLabelStyle(item)"
        :key="index"
        @click="onLabelItemClick(item)"
        :title="item.label"
      >
        <span v-text="item.label"></span>
      </div>
    </template>
  </div>
</template>
<script lang="ts">
import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import * as d3 from "d3";

@Component({
  name: "ChartLabel",
  components: {}
})
export default class ChartLabel extends Vue {
  @Prop()
  private option!: ComplexLabelColumn;

  @Prop()
  private range!: [number, number];

  private h!: number;
  private w!: number;

  private scale!: d3.ScaleLinear<any, any, any>;
  private inited: boolean = false;

  onLabelItemClick(data: ComplexLabelItem) {
    if (this.option.onClick) {
      this.option.onClick(data);
    }
  }

  @Watch("option", { immediate: true })
  onOptionEntry() {
    this.inited = false;
    this.$nextTick(() => {
      this.start();
    });
  }

  start() {
    const rect = this.$el.getBoundingClientRect();
    this.h = rect.height;
    this.w = rect.width;

    this.scale = d3.scaleLinear().range([0, this.h]).domain(this.range);
    this.inited = true;
  }

  getLabelStyle(item: ComplexLabelItem) {
    const start = this.scale(item.range[0]);
    const end = this.scale(item.range[1]);
    const height = end - start;
    const style: any = {
      height: height + "px",
      top: start + "px",
      backgroundColor: item.backgroundColor || "#ffff",
      color: this.option.fontColor || "#000",
      fontSize: (this.option.fontSize || 14) + "px",
      fontWeight: this.option.fontWeight || "normal"
    };
    if (item.fontColor) {
      style.color = item.fontColor;
    }
    if (item.backgroundImage && item.backgroundImage.length > 0) {
      // console.log(style);
      style.backgroundImage = `url(${item.backgroundImage})`;
      style.backgroundPosition = "center center";
      style.backgroundSize = "contain";
      style.backgroundRepeat = "no-repeat";
    }
    return style;
  }
}
</script>
<style lang="scss" scoped>
.chart-inst {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  .label-item {
    position: absolute;
    width: 100%;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 10px;
    word-break: break-all;
    box-sizing: border-box;
    text-align: center;
    border-bottom: 1px solid #000;
    box-sizing: border-box;
    overflow: hidden;
    &:first-child {
      border-top: 1px solid #000;
    }
  }
}
</style>
